<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible" @close="onClose">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
      label-width="80px">
      <el-form-item label="商品id" prop="spuId">
        <el-input v-model="dataForm.spuId" placeholder="商品id"></el-input>
      </el-form-item>
      <el-form-item label="图片集合" prop="imgUrls">
        <!-- <el-input v-model="dataForm.imgUrls" placeholder="图片集合（json格式）"></el-input> -->
        <el-upload class="upload-demo" ref="upload" action="http://localhost:88/api/oss/upload" :show-file-list="true"
          :file-list="fileList" accept=".jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG" :on-success="handle_success"
          :before-remove="hadle_remove" list-type="picture" :auto-upload="true">
          <el-button>选择文件</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="图片类型" prop="imgType">
        <el-input v-model="dataForm.imgType" placeholder="图片类型（1.商品banner2.商品介绍）"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="onClose()">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      fileList: [],
      dataForm: {
        id: 0,
        spuId: '',
        imgUrls: '',
        imgType: ''
      },
      dataRule: {
        spuId: [
          { required: true, message: '商品id不能为空', trigger: 'blur' }
        ],
        imgUrls: [
          { required: true, message: '图片集合（json格式）不能为空', trigger: 'blur' }
        ],
        imgType: [
          { required: true, message: '图片类型（1.商品banner2.商品介绍）不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init(id) {
      this.dataForm.id = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/product/productimgs/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 200) {
              console.log(data);

              this.dataForm.spuId = data.productImgs.spuId
              // this.dataForm.imgUrls = data.productImgs.imgUrls
              this.dataForm.imgUrls = JSON.parse(data.productImgs.imgUrls)
              this.dataForm.imgType = data.productImgs.imgType
              // 将json字符串转化为数组数据
              let arr = this.dataForm.imgUrls
              // 赋值到文件列表中
              this.fileList = arr.map(element => {
                return { name: element, url: element }
              })

            }
          })
        }
      })
    },
    onClose() {
      this.visible = false
      this.fileList = []
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/product/productimgs/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'id': this.dataForm.id || undefined,
              'spuId': this.dataForm.spuId,
              'imgUrls': JSON.stringify(this.dataForm.imgUrls),
              'imgType': this.dataForm.imgType
            })
          }).then(({ data }) => {
            if (data && data.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.fileList = []
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },



    // 修改显示最新图片
    // fileChange(file, fileList) {
    //   // 这是关键一句
    //   if (imgList.length > 0) {
    //     this.fileList = [fileList[fileList.length - 1]]
    //   }
    // },

    // 上传成功回调
    handle_success(res) {
      console.log(res)
      this.$message.success('图片上传成功')

      // 上传成功后，将图片地址赋值给dataForm.mainImage
      this.dataForm.imgUrls.push(res.data)
      // this.dataForm = res.data
    },
    //上传组件删除回调
    hadle_remove(file, fileList) {

      // console.log('file', file);
      // console.log('fileList', fileList.length);

      this.dataForm.imgUrls.splice(this.dataForm.imgUrls.indexOf(file), 1)

      console.log("修改后的 this.dataForm.imgUrls", this.dataForm.imgUrls);

    }
  },



  // watch: {
  //   fileList(newValue, oldValue) {
  //     console.log(oldValue)
  //     console.log(newValue)
  //   }
  // }
}
</script>
